package com.x.erp.dao;

import com.x.erp.model.ShareTemplate;
import com.x.framework.dao.BaseDao;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * 分享模板信息
 */
@Repository
public class ShareTemplateDao extends BaseDao {

	private String selectShareTemplateSql = "SELECT " +
			"est.*, " +
			"es.SHOP_NAME, " +
			"es.SHOP_ADDRESS, " +
			"es.MARKET_ID, " +
			"eu.USER_NAME, " +
			"eu.USER_MOBILE " +
			"FROM ERP_SHARE_TEMPLATE est " +
			"LEFT JOIN ERP_SHOP es ON est.SHOP_ID = es.SHOP_ID " +
			"LEFT JOIN ERP_USER eu ON est.USER_ID = eu.USER_ID " +
			"WHERE 1=1 ";
	/**
	 * 查询表分享模板信息
	 * @param shareTemplate
	 * @return
	 * @throws Exception
	 */
	public ShareTemplate selectShareTemplate(ShareTemplate shareTemplate) throws  Exception {
		StringBuilder sql = new StringBuilder(selectShareTemplateSql);
		List<Object> params = new ArrayList<>();
		selectSearch(sql, params, shareTemplate);
		List<ShareTemplate> res = this.queryForList(sql.toString(), ShareTemplate.class, params, shareTemplate);
		if(res == null || res.size() == 0){
			return null;
		}
		return res.get(0);
	}

	private String selectShareTemplateListSql = "SELECT est.* FROM ERP_SHARE_TEMPLATE est WHERE 1=1 ";
	/**
	 * 查询分享模板信息列表
	 * @param shareTemplate
	 * @return
	 * @throws Exception
	 */
	public List<ShareTemplate> selectShareTemplateList(ShareTemplate shareTemplate) throws  Exception {
		StringBuilder sql = new StringBuilder(selectShareTemplateSql);
		List<Object> params = new ArrayList<>();
		selectSearch(sql, params, shareTemplate);
		return this.queryForList(sql.toString(), ShareTemplate.class, params, shareTemplate);
	}

	private void selectSearch(StringBuilder sql, List<Object> params, ShareTemplate shareTemplate) {
		if(this.isString(shareTemplate.getShareId())){
			sql.append("AND est.SHARE_ID = ? ");
			params.add(shareTemplate.getShareId());
		}
		if(this.isString(shareTemplate.getUserId())){
			sql.append("AND est.USER_ID = ? ");
			params.add(shareTemplate.getUserId());
		}
		if(this.isString(shareTemplate.getShopId())){
			sql.append("AND est.SHOP_ID = ? ");
			params.add(shareTemplate.getShopId());
		}
	}
}
